import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import moment from 'moment';
import md5 from 'md5';

const router = new Router();
router.prefix('/ad/api');

router.post('/:table/insert', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let isExist = false;
    switch (ctx.params.table) {
        case 'role':
            if (body.role_name == null) {
                ctx.body = response.fail('缺少必填字段 角色名称');
                return;
            }
            if (body.role_value == null) {
                ctx.body = response.fail('缺少必填字段 角色值');
                return;
            }
            isExist = await db.checkExist('role', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同级别相同名称的角色已存在');
                return;
            }
           // body.create_time = moment().format('YYYY-MM-DD HH:mm:ss');
            break; 
        case 'dictionary':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 字典名称');
                return;
            }
            if (body.value == null) {
                ctx.body = response.fail('缺少必填字段 字典标识');
                return;
            }
            // isExist = await db.checkExist('dictionary', { name: body.name });
            // if (isExist) {
            //     ctx.body = response.fail('相同名称的数据字典已存在');
            //     return;
            // }
            body.create_time = moment().format('YYYY-MM-DD HH:mm:ss');
            break;
        case 'dictionary_detial':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 字典详情名称');
                return;
            }
            isExist = await db.checkExist('dictionary_detial', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同名称的数据字典详情已存在');
                return;
            }
            break;
        case 'enterprise':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 企业名称');
                return;
            }
            isExist = await db.checkExist('enterprise', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同企业已存在');
                return;
            }
            break;
        case 'workers':
            if (body.account == null) {
                ctx.body = response.fail('缺少必填字段 帐号');
                return;
            }
            isExist = await db.checkExist('workers', { account: body.account });
            if (isExist) {
                ctx.body = response.fail('相同帐号的员工已存在');
                return;
            }
            if (body.password) {
                body.password = md5(body.password);
            }
            break;
        case 'evaluator':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 名称');
                return;
            }
            if (body.password) {
                body.password = md5(body.password);
            }
            break;
        case 'order_info':
            //生成12位数字订单号
            body.id = Math.random().toString().slice(2, 14);
            break;
        default:
            break;
    }
    let res = await db.create(ctx.params.table, body);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} create error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} create error :` + res.message);
        return;
    }
    if (ctx.params.table == 'order_info') {
        ctx.body = response.success({ id: body.id });
    } else {
        ctx.body = response.success({ id: res.insertId });
    }
});
function getConditions(tbaleName, body) {
    let conditions = {};
    //根据不同的表获取表的主键用于后续的更新和删除
    switch (tbaleName) {
        case 'oper':
            if (body.account == null) {
                return { code: 0, conditions, msg: '缺少必填字段 account' };
            }
            conditions = { account: body.account };
            return { code: 1, conditions: conditions };
        case "isp_info":
            if(body.isp_code == null){
                return { code: 0, conditions, msg: '缺少必填字段 isp_code' };
            }
            conditions = { isp_code: body.isp_code };
            return { code: 1, conditions: conditions };
        case 'user_info':
            if (body.openid == null) {
                return { code: 0, conditions, msg: '缺少必填字段 openid' };
            }
            conditions = { openid: body.openid };
            return { code: 1, conditions: conditions };
        default:
            if (body.id == null) {
                return { code: 0, conditions, msg: '缺少必填字段 id' };
            }
            conditions = { id: body.id };
            return { code: 1, conditions: conditions };
    }
}

router.post('/:table/update', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    let obj = await db.findOne(ctx.params.table, conditions);
    if (obj == null) {
        ctx.body = response.fail('要修改数据不存在');
        return;
    }
    // for (let key in body) {
    //     if (body[key] != undefined && body[key] != null) {
    //         obj[key] = body[key];
    //     }
    // }
    delete body.conditions;
    
    res = await db.update(ctx.params.table, body, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} update error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/:table/remove', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    res = await db.deleteRow(ctx.params.table, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} delete error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} delete error :` + res.message);
        return;
    }
    if (ctx.params.table == 'device') {
        memDB.deleteDevice({ sn: body.sn });
    }
    ctx.body = response.success();
});
router.post('/:table/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' };
    } else {
        if (!body.direction) body.direction = 'desc';
    }
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    let res = await db.findAll(ctx.params.table, body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr,body.dispColumn,body.customizeWhere);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} getList error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} getList error :` + res.message);
        return;
    }
    if (res.count) {
        ctx.body = response.success({ rows: res.rows, count: res.count });
        return;
    } else {
        ctx.body = response.success(res);
    }
});



export { router };
